<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------



// 应用公共文件
if(!function_exists('_unsetNull')){
	//null转空字符串
	function _unsetNull($arr){
	    if($arr !== null){
	        if(is_array($arr)){
	            if(!empty($arr)){
	                foreach($arr as $key => $value){
	                    if($value === null){
	                        $arr[$key] = '';
	                    }else{
	                        $arr[$key] = _unsetNull($value);      //递归再去执行
	                    }
	                }
	            }else{ $arr = []; }
	        }else{
	            if($arr === null){ $arr = []; }         //注意三个等号
	        }
	    }else{
	    	 $arr = []; 
		}
	    return $arr;
	}
}

/**
 * 对字符串或者数组进行检验检测
 */
if(!function_exists('getParam')){
	//可以对字符串进行sql检测，也可以对数据进行数据检测
	function getParam($key) {   
		$v	= addslashes(is_null($_GET[$key])?$_POST[$key]:$_GET[$key]);
		return $v;
	}   
}
/**
 * 对字符串或者数组进行检验检测
 */
if(!function_exists('daddslashes')){
	//可以对字符串进行sql检测，也可以对数据进行数据检测 防止sql注入
	function daddslashes($string, $force = 0) {   
		if(!$GLOBALS['magic_quotes_gpc'] || $force) {   
			if(is_array($string)) {   
				foreach($string as $key => $val) {   
					$string[$key] = daddslashes($val, $force);   
				}   
			} else {   
				$string = addslashes($string);   
			}   
		}   
		return $string;   
	}   
}
 /**
     * 生成唯一的订单号 20110809111259232312
     * 2011-年日期
     * 08-月份
     * 09-日期
     * 11-小时
     * 12-分
     * 59-秒
     * 2323-微秒
     * 12-随机值
     * @return string
     */
if(!function_exists('orderNO')){
    function orderNO() {
        list($usec, $sec) = explode(" ", microtime());
        $usec = substr(str_replace('0.', '', $usec), 0 ,4);
        $str  = rand(10,99);
        return date("YmdHis").$usec.$str;
    }
}

//保留2位小数点， formatNumber(123.2256) -> 123.23  formatNumber(123) -> 123.00  ;
if(!function_exists('formatNumber')){
	function formatNumber($number,$count){
		return  number_format($number, $count, '.', '');
	}
}

//工龄
if(!function_exists('emploeeAge')){
	function emploeeAge($empDate){
		if(empty($empDate) || startWith($empDate,"0000")){
			return "";
		}else{
			$nowt = time();
			$entr = strtotime($empDate);
			
			$dd = $nowt-$entr;
			$dd = floor($dd/31536000);
			return $dd;
		}
		
	}
}

//字符串是否开头
if(!function_exists('startWith')){
	function startWith($bigStr, $findStr) {
    		return strpos($bigStr, $findStr) === 0;
	}
}

//字符串是否结尾
if(!function_exists('endWith')){
	function endWith($haystack, $needle) {   
	      $length = strlen($needle);  
	      if($length == 0)
	      {    
	          return true;  
	      }  
	      return (substr($haystack, -$length) === $needle);
 	}
}

if(!function_exists('str_insert')){
	function str_insert($str, $i, $substr){
		for($j=0; $j<$i; $j++){
			$startstr .= $str[$j];
		}
		for ($j=$i; $j<mb_strlen($str); $j++){
		    $laststr .= $str[$j];
		}
		$str = ($startstr . $substr . $laststr);
		return $str;
	}
}

if(!function_exists('checkPermission')){
	function checkPermission($code) {
		$permission = $_SESSION['permission'];
		if(stripos($permission,"_".$code."_")!== FALSE){
			return TRUE;
		}else{
			return FALSE;
		}
	}
}

 
if(!function_exists('array_removeByKey')){
	function array_removeByKey($data, $key) {
		if(!array_key_exists($key, $data)){  
	        return $data;  
	    }  
	    $keys = array_keys($data);  
	    $index = array_search($key, $keys);  
	    if($index !== FALSE){  
	        array_splice($data, $index, 1);  
	    }  
	    return $data; 
	}
}
	
	
if(!function_exists('pad_stringLeft')){
	function pad_stringLeft($sourceNumber,$numlength) {
		$format = "%0".$numlength."d";
		$var1=sprintf($format, $sourceNumber);
		return $var1;
	}
}

if(!function_exists('str_replace_limit')){
	/** 
	 * 对字符串执行指定次数替换 
	 * @param Mixed $search  查找目标值 
	 * @param Mixed $replace 替换值 
	 * @param Mixed $subject 执行替换的字符串／数组 
	 * @param Int  $limit  允许替换的次数，默认为-1，不限次数 
	 * @return Mixed 
	 */
	function str_replace_limit($search, $replace, $subject, $limit=-1){ 
	  if(is_array($search)){ 
	    foreach($search as $k=>$v){ 
	      $search[$k] = '`'. preg_quote($search[$k], '`'). '`'; 
	    } 
	  }else{ 
	    $search = '`'. preg_quote($search, '`'). '`'; 
	  } 
	  return preg_replace($search, $replace, $subject, $limit); 
	} 
}
if(!function_exists('eeGetDate')){
	function eeGetDate() {
		return date("Y-m-d");
	}
}
if(!function_exists('eeGetDateTime')){
	function eeGetDateTime() {
		return date("Y-m-d H:i:s");
	}
}

if(!function_exists('doGetRequest')){
	function doGetRequest($host,$port,$request) {
		$httpGet  = "GET ". $request. " HTTP/1.1\r\n";
		$httpGet .= "Host: $host\r\n";
		$httpGet .= "Connection: Close\r\n";
		//	$httpGet .= "User-Agent: Mozilla/4.0(compatible;MSIE 7.0;Windows NT 5.1)\r\n";
		$httpGet .= "Content-type: text/plain\r\n";
		$httpGet .= "Content-length: " . strlen($request) . "\r\n";
		$httpGet .= "\r\n";
		$httpGet .= $request;
		$httpGet .= "\r\n\r\n";
		return httpSend($host,$port,$httpGet);
	}
}
	
if(!function_exists('doGet')){
	function doGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
		
		return json_decode($res,TRUE);
		
		//$res = '{"access_token":"6_Rdayv8aG3i58gUPIKwd94kfi9wjD_uTy-tlb-NrFJSvYrYwlKvi7_0LAFm-dHCbnjNKjler6NCFKkbX7wLu7mfgluJWE85iftclp1au5mhLstiWGL7pRV47pcPsYr9KiLqHd3CS6W0AsWcl2HAWfADATMI","expires_in":7200}';
		//$wxobj = json_decode($res);
		
	}
}

if(!function_exists('doPostRequest')){
	function doPostRequest($host,$port,$request) {
		$content = substr($request,1+stripos($request,"?"));
		$httpPost  = "POST ". substr($request,0,stripos($request,"?")). " HTTP/1.1\r\n";
		$httpPost .= "Host: $host\r\n";
		$httpPost .= "Connection: Close\r\n";
		//	$httpPost .= "User-Agent: Mozilla/4.0(compatible;MSIE 7.0;Windows NT 5.1)\r\n";
		$httpPost .= "Content-type: application/x-www-form-urlencoded\r\n";
		$httpPost .= "Content-length: " . strlen($content) . "\r\n";
		$httpPost .= "\r\n";
		$httpPost .= $content;
		$httpPost .= "\r\n\r\n";
		return httpSend($host,$port,$httpPost);
	}
}
	
if(!function_exists('httpSend')){
	/**
	 * 使用http协议发送消息
	 *
	 * @param string $host
	 * @param int $port
	 * @param string $request
	 * @return string
	 */
	function httpSend($host,$port,$request) {
		$result = "";
		$fp = @fsockopen($host, $port,$errno,$errstr,5);
		if ( $fp ) {
			fwrite($fp, $request);
			while(! feof($fp)) {
				$result .= fread($fp, 1024);
			}
			fclose($fp);
		}
		else
		{
			return "连接网关超时！";//超时标志
		}
		list($header, $foo)  = explode("\r\n\r\n", $result);
		list($foo, $content) = explode($header, $result);
		$content=str_replace("\r\n","",$content);
		//返回调用结果
		
		
		return $content;
	}
}

if(!function_exists('encodeHexStr')){
	/**
	 * encode Hex String
	 *
	 * @param string $dataCoding
	 * @param string $binStr
	 * @param string $encode
	 * @return string hex string
	 */
	function encodeHexStr($dataCoding,$binStr,$encode="UTF-8"){
		//return bin2hex($binStr);
		if ($dataCoding == 15) {//GBK
			return bin2hex(mb_convert_encoding($binStr,"GBK",$encode));
		} elseif (($dataCoding & 0x0C) == 8) {//UCS-2BE
			return bin2hex(mb_convert_encoding($binStr,"UCS-2BE",$encode));
		} else {//ISO8859-1
			return bin2hex(mb_convert_encoding($binStr,"ASCII",$encode));
		}
	}
}

if(!function_exists('decodeHexStr')){
	/**
	 *  decode Hex String
	 *
	 * @param string $dataCoding
	 * @param string $hexStr
	 * @param string $encode
	 * @return string binary string
	 */
	function decodeHexStr($dataCoding,$hexStr,$encode="GBK"){
		// only hex numbers is allowed
		if (strlen($hexStr) % 2 != 0 || preg_match("/[^\da-fA-F]/",$hexStr)) return FALSE;
		
		$buffer=array();
		if ($dataCoding == 15) {//GBK
			for($i=0;$i<strlen($hexStr);$i+=2){
				if(hexdec(substr($hexStr,$i,2))>=0xa1){//0xa1-0xfe
					$buffer[]=iconv("GBK",$encode,pack("H4",substr($hexStr,$i,4)));
					$i+=2;
				}else{
					$buffer[]=iconv("ISO8859-1",$encode,pack("H2",substr($hexStr,$i,2)));
				}
			}
		} elseif (($dataCoding & 0x0C) == 8) {//UCS-2BE
			for($i=0;$i<strlen($hexStr);$i+=4){
				$buffer[]=iconv("UCS-2BE",$encode,pack("H4",substr($hexStr,$i,4)));
			}
		} else {//ISO8859-1
			for($i=0;$i<strlen($hexStr);$i+=2){
				$buffer[]=iconv("ASCII",$encode,pack("H2",substr($hexStr,$i,2)));
			}
		}
		return join("",$buffer);
	}
}


/**
 * 唯一id
 */
if(!function_exists('guid')){
	function guid() {
	    list($usec, $sec) = explode(" ", microtime());  
	    $guid = $prefix. $factor. $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']  
	           . $sec . $usec   
	           . mt_rand(0,1000000).time(). mt_rand(0,1000000).$suffix;  
	    $guid = substr(sha1($guid),8,32); 
	    $guid = base_convert($guid,16,36);  
	    return $prefix.$guid.$suffix;
	}
}
/**
 * 唯一标示符
 */
if(!function_exists('create_unique')){
	function create_unique() {
	    $data = $_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].time().rand();
		return sha1($data);//return md5(time().$data);   //return $data;
	}
}
/**
 * 为空则返回0
 */
if(!function_exists('eric_num')){
	function eric_num($num) {
		if(isset($num) && !empty($num)){
			return $num;
		}else{
			return 0;
		}
	}
}
	
if(!function_exists('Nu')){
	function Nu($msg) {
		if(isset($msg)){
			return $msg;
		}
	}
}


if(!function_exists('print_msg')){
	function print_msg($msg) {
		if ($msg) {
			echo "<p class=\"bg-info\" style=\"padding:15px;\">$msg</p>";
		} else {
			return false;
		}
	}
}

if(!function_exists('print_error')){
	function print_error($msg) {
		if ($msg) {
			echo "<p class=\"bg-danger\" style=\"padding:15px;\">$msg</p>";
		} else {
			return false;
		}
	}
}

if(!function_exists('print_warning')){
    function print_warning($msg) {
        if ($msg) {
            echo "<p class=\"bg-warning\" style=\"padding:15px;\">$msg</p>";
        } else {
            return false;
        }
    }
}

if(!function_exists('print_success')){
    function print_success($msg) {
        if ($msg) {
            echo "<p class=\"bg-success\" style=\"padding:15px;\">$msg</p>";
        } else {
            return false;
        }
    }
}

if(!function_exists('dump')){
	function dump($msg) {
		echo "<pre>";
		print_r($msg);
		echo "</pre>";
	}
}

if(!function_exists('js_alert')){
	function js_alert($info = "", $url = "") {
		echo "<script type=\"text/javascript\">alert('$info');</script>";
		if (!empty($url)) {
			echo "<meta http-equiv=\"Refresh\" content=\"0;URL={$url}\">";
			exit();
		}
	}
}

if(!function_exists('js_goback')){
	function js_goback($text = "") {
		echo "<script type=\"text/javascript\">alert('$text'); history.go(-1)</script>";
		exit;
	}
}

/**
check email formate
*/
if(!function_exists('is_email')){
	function is_email($email) {
		return strlen($email) > 6 && preg_match("/^[\w\-\.&]+@[\w\-]+(\.\w+)+$/", $email);
	}
}

/**
check email formate
*/
if(!function_exists('is_phone')){
	function is_phone($phonenumber) {
		if(preg_match("/^1\d{10}$/",$phonenumber)){  
		    return TRUE;
		}else{  
			return FALSE;  
		}
	}
}


/**
copy image and save to new folder
*/
if( !function_exists('copyNewImage') ){
	function copyNewImage($imageName,$new_image_folder='',$newWidth=150,$newHeight=200){
		list($width, $height,$type) = getimagesize($imageName);
		if ( $width>$newWidth || $height>$newHeight ) {
			 if ($width/$newWidth > $height/$newHeight ) {
			 	 $newHeight = $newWidth*$height/$width;
			 	 $newWidth = $newWidth;
			 }else{
			 	 $newWidth = $newHeight*$width/$height;
			 	 $newHeight = $newHeight;
			 }
			 
		}
		switch($type){
			case 1: $source = imagecreatefromgif($imageName);
					break;
			case 2: $source = imagecreatefromjpeg($imageName);
					break;				
			case 3: $source = imagecreatefrompng($imageName);
					break;	
		}
		$thumb = imagecreatetruecolor($newWidth, $newHeight);
		imagecopyresized($thumb,$source,0,0,0,0,$newWidth,$newHeight,$width,$height);
		//get name
		$image_array = explode('/',$imageName);
		$image_name_for_thumb = $image_array[count($image_array)-1];
		//set new image folder
		if(!empty($new_image_folder)){
			if (!file_exists($new_image_folder)) {
				mkdir($new_image_folder);
			}		
			if ($new_image_folder == $folder) {
				 $new_image_folder = $new_image_folder.'thumb';
			}
			
			$newFileName=$new_image_folder.'/'.$image_name_for_thumb;
		}else{
			if (!file_exists('thumb_image')) {
				mkdir('thumb_image');
			}	
			$newFileName='thumb_image/'.$image_name_for_thumb;
		}
		//export image to folder
		if ( !file_exists($newFileName) ) {
			switch($type){
				case 1: imagegif($thumb,$newFileName);
						break;
				case 2: imagejpeg($thumb,$newFileName);
						break;				
				case 3: imagepng($thumb,$newFileName);
						break;			
			}	
		}else{
			js_goback('The New Thumb image exists!');
		}	
	}
}


/**
get image new width and height according to defined image width and height
*/
if(!function_exists('image_new_width_height')){
	function image_new_width_height($image='',$new_width="120",$new_height="100"){
		if (is_file($image)) {
			list($width, $height, $type, $attr) = getimagesize($image);
			if ($width<=$new_width && $height<=$new_height) {
				$out_width=$width;
				$out_height=$height;
			}elseif($width*1.0/$height<=$new_width*1.0/$new_height) {
				$out_height=$new_height;
				$out_width=$width*($new_height/$height);
			}else{
				$out_width=$new_width;
				$out_height=$height*($new_width/$width);
			}
			$image_attr[]=$out_width;
			$image_attr[]=$out_height;
			return $image_attr;
		}
	}
}


/***
check whether two dimensional array is empty
*/
if(!function_exists('check_array_empty')){
	function check_array_empty($arr){
		if(is_array($arr)){
			foreach($arr AS $v){
				if(!empty($v) || $v == 0 || $v == "0"){
					return false;
					break;
				}
			}
			return true;
		}
	}
}


/*
 * Grab remote pictures to local
 */
if(!function_exists('GrabImage')){
	function GrabImage($url,$filename="") {
		if($url==""):return false;endif;
		
		if($filename=="") {
			$ext_arr = array('.gif','.jpg','.png');
			$ext=strrchr($url,".");
			if(!in_array($ext, $ext_arr)):return false;endif;
			$filename=date("dMYHis").$ext;
		}
		
		ob_start();
		readfile($url);
		$img = ob_get_contents();
		ob_end_clean();
		$size = strlen($img);
		
		$fp2=@fopen($filename, "a");
		fwrite($fp2,$img);
		fclose($fp2);
	
	return $filename;
	}
}

	
/*
* get the specified number of words (English words)
*/
if(!function_exists('subwords')){
	function subwords($words,$num){
	$total_num = str_word_count($words); 

	if($total_num <= $num){   
	return $words;
	}else{
	$pattern = '/([\S]+?[ ]+){'.$num.'}/';
	preg_match($pattern, $words, $out);
	return $out[0].'...'; 
	}

	}
}
/*
* get the specified number of words (UTF8 words)
*/
if(!function_exists('utf8Substr')){
	function utf8Substr($str, $from, $len){
	    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
	                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
	                       '$1',$str);
	}
}

/*upload one file to server. if upload successed, will return the random filename.
parm:
field:the input field's name;
uploaddir: upload folder
*/

if(!function_exists('upload_one_file')){
	function upload_one_file($field,$uploaddir,$obj){
		//upload one file
		//$uploaddir = '/var/www/uploads/';
		mt_srand();
		$uploadfile = md5(uniqid(mt_rand())). get_extension($_FILES[$field]['name']);
		if (move_uploaded_file($_FILES[$field]['tmp_name'], $uploaddir.$uploadfile)) 
		{
		   return $uploadfile;
		} 
		else 
		{
		   return false;
		}
		
	}
}

/*get file's ext name*/
if(!function_exists('get_extension'))
{
	function get_extension($filename)
	{
		$x = explode('.', $filename);
		return '.'.end($x);
	}
}

/*get document root upload path*/	
	
if(!function_exists('get_root'))
{
	function get_root($str='')
	{
		if($str=='')
			return $_SERVER['DOCUMENT_ROOT'].'/ci2_cms/demo/userfiles';
		else
			return $_SERVER['DOCUMENT_ROOT'].'/ci2_cms/demo/'.$str.'/';
	}
}


if ( ! function_exists('force_http'))
{
    function force_http()
    {
        $CI =& get_instance();
        $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] == 443)
        {
            redirect($CI->uri->uri_string());
        }
    }
}  
if ( ! function_exists('force_ssl'))
{
    function force_ssl()
    {
        $CI =& get_instance();
        $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] != 443)
        {
            redirect($CI->uri->uri_string());
        }
    }
}  

if ( ! function_exists('h'))
{
    function h($str)
    {
		return	htmlspecialchars($str);
    }
} 

if ( ! function_exists('uh'))
{
    function uh($str)
    {
		return	htmlspecialchars_decode($str);
    }
} 

if ( ! function_exists('pageConfig'))
{
    function pageConfig($base_url, $total_rows, $per_page, $cur_page)
    {
    	$config = array();
		$config['base_url'] = $base_url;
        $config['total_rows'] = $total_rows;
        $config['per_page'] = $per_page;
        $config['cur_page'] = $cur_page;
        $config['first_link'] = '首页';
        $config['full_tag_open'] = '<ul class="pagination">';
        $config['full_tag_close'] = '</ul>';
        $config['first_tag_open'] = '<li>';//“第一页”链接的打开标签。
        $config['first_tag_close'] = '</li>';//“第一页”链接的关闭标签。
        $config['last_link'] = '尾页';//你希望在分页的右边显示“最后一页”链接的名字。
        $config['last_tag_open'] = '<li>';//“最后一页”链接的打开标签。
        $config['last_tag_close'] = '</li>';//“最后一页”链接的关闭标签。
        $config['next_link'] = '下一页';//你希望在分页中显示“下一页”链接的名字。
        $config['next_tag_open'] = '<li>';//“下一页”链接的打开标签。
        $config['next_tag_close'] = '</li>';//“下一页”链接的关闭标签。
        $config['prev_link'] = '上一页';//你希望在分页中显示“上一页”链接的名字。
        $config['prev_tag_open'] = '<li>';//“上一页”链接的打开标签。
        $config['prev_tag_close'] = '</li>';//“上一页”链接的关闭标签。
        $config['cur_tag_open'] = '<li class="active"><a href="#">';//“当前页”链接的打开标签。
        $config['cur_tag_close'] = '</a></li>';//“当前页”链接的关闭标签。
        $config['num_tag_open'] = '<li>';//“数字”链接的打开标签。
        $config['num_tag_close'] = '</li>';
        return $config;
    }
} 


if ( ! function_exists('array_to_object'))
{
/**
 * 数组 转 对象
 * @param array $arr 数组
 * @return object
 */
	function array_to_object($arr) {
	    if (gettype($arr) != 'array') {
	        return;
	    }
	    foreach ($arr as $k => $v) {
	        if (gettype($v) == 'array' || getType($v) == 'object') {
	            $arr[$k] = (object)array_to_object($v);
	        }
	    }
	 
	    return (object)$arr;
	}
}


if ( ! function_exists('object_to_array')){
/**
 * 对象 转 数组
 * @param object $obj 对象
 * @return array
 */
	function object_to_array($obj) {
	    $obj = (array)$obj;
	    foreach ($obj as $k => $v) {
	        if (gettype($v) == 'resource') {
	            return;
	        }
	        if (gettype($v) == 'object' || gettype($v) == 'array') {
	            $obj[$k] = (array)object_to_array($v);
	        }
	    }
	 
	    return $obj;
	}
}
if ( ! function_exists('read_csv_lines')){
	/**
	 * 读取CSV文件
	 * @param string $csv_file csv文件路径
	 * @param int $lines       读取行数
	 * @param int $offset      起始行数
	 * @return array|bool
	 */
	 function read_csv_lines($csv_file = '', $lines = 0, $offset = 0)
	{
	    if (!$fp = fopen($csv_file, 'r')) {
	        return false;
	    }
	    $i = $j = 0;
	    while (false !== ($line = fgets($fp))) {
	        if ($i++ < $offset) {
	            continue;
	        }
	        break;
	    }
	    $data = array();
	    while (($j++ < $lines) && !feof($fp)) {
	        $data[] = fgetcsv($fp);
	    }
	    fclose($fp);
	    return $data;
	}
}
/**
 * 导出CSV文件
 * @param array $data        数据
 * @param array $header_data 首行数据
 * @param string $file_name  文件名称
 * @return string
 */
if ( ! function_exists('export_csv_1')){
	 function export_csv_1($data = [], $header_data = [], $file_name = '')
	{
	    header('Content-Type: application/octet-stream');
	    header('Content-Disposition: attachment; filename=' . $file_name);
	    if (!empty($header_data)) {
	        echo iconv('utf-8','gbk//TRANSLIT','"'.implode('","',$header_data).'"'.PHP_EOL);
	    }
	    foreach ($data as $key => $value) {
	        $output = array();
	        $output[] = $value['id'];
	        $output[] = $value['name'];
	        echo iconv('utf-8','gbk//TRANSLIT','"'.implode('","', $output).PHP_EOL);
	    }
	}
}

if ( ! function_exists('humenFormatTime')){
	//人性化时间显示  
	function humenFormatTime($time){       
	    $rtime = date("m-d H:i",$time);       
	    $htime = date("H:i",$time);             
	    $time = time() - $time;         
	    if ($time < 60){           
	        $str = '刚刚';       
	    }elseif($time < 60 * 60){           
	        $min = floor($time/60);           
	        $str = $min.'分钟前';       
	    }elseif($time < 60 * 60 * 24){           
	        $h = floor($time/(60*60));           
	        $str = $h.'小时前 ';       
	    }elseif($time < 60 * 60 * 24 * 3){           
	        $d = floor($time/(60*60*24));           
	        if($d==1){  
	            $str = '昨天 '.$rtime;  
	        }else{  
	            $str = '前天 '.$rtime;       
	        }  
	    }else{           
	        $str = $rtime;       
	    }       
	    return $str;   
	}  
}

if ( ! function_exists('export_csv_2')){
	/**
	 * 导出CSV文件
	 * @param array $data        数据
	 * @param array $header_data 首行数据
	 * @param string $file_name  文件名称
	 * @return string
	 */
	 function export_csv_2($data = [], $header_data = [], $file_name = '')
	{
	    header('Content-Type: application/vnd.ms-excel');
	    header('Content-Disposition: attachment;filename='.$file_name);
	    header('Cache-Control: max-age=0');
	    $fp = fopen('php://output', 'a');
	    if (!empty($header_data)) {
	        foreach ($header_data as $key => $value) {
	            $header_data[$key] = iconv('utf-8', 'gbk', $value);
	        }
	        fputcsv($fp, $header_data);
	    }
	    $num = 0;
	    //每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
	    $limit = 100000;
	    //逐行取出数据，不浪费内存
	    $count = count($data);
	    if ($count > 0) {
	        for ($i = 0; $i < $count; $i++) {
	            $num++;
	            //刷新一下输出buffer，防止由于数据过多造成问题
	            if ($limit == $num) {
	                ob_flush();
	                flush();
	                $num = 0;
	            }
	            $row = $data[$i];
	            foreach ($row as $key => $value) {
	                $row[$key] = iconv('utf-8', 'gbk', $value);
	            }
	            fputcsv($fp, $row);
	        }
	    }
	    fclose($fp);
	}
}
	